package com.baohulu.baohulu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

import com.baohulu.baohulu.R;
import com.baohulu.baohulu.base.BaseActivity;
import com.baohulu.baohulu.base.BaseResponseCallback;
import com.baohulu.baohulu.common.Const;
import com.baohulu.baohulu.utils.HttpUtil;
import com.baohulu.baohulu.utils.JsonUtil;
import com.baohulu.baohulu.utils.TimeUtil;
import com.baohulu.baohulu.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.baohulu.baohulu.common.Const.LOOP_TIMES;

/**
 * 开锁后的计时界面
 */
public class TimerActivity extends BaseActivity {
    private static final String TAG = "TimerActivity";
    @BindView(R.id.rented_time)
    TextView tvRentedTime;
    @BindView(R.id.cost)
    TextView tvCost;
    private long startTime = 0;
    private double price = 0;
    private String ballKey = "";
    private String eqKey = "";
    private int doorId = -1;
    private Timer timer;
    private TimerTask timerTask;
    private boolean isReturnSuccess = false;
    private int times = LOOP_TIMES;

    private long rentTime = -1;
    private double cost = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);
        ButterKnife.bind(this);
        startTime = getIntent().getLongExtra(Const.Extra.START_TIME, System.currentTimeMillis());
        price = getIntent().getDoubleExtra(Const.Extra.BALL_PRICE, 0);
        ballKey = getIntent().getStringExtra(Const.Extra.BALL_KEY);
        eqKey = getIntent().getStringExtra(Const.Extra.EQ_KEY);
        doorId = getIntent().getIntExtra(Const.Extra.DOOR_INDEX, -1);
        timer = new Timer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        timerTask.cancel();
        timerTask = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                long nowInSecond = System.currentTimeMillis() / 1000 + 1;
                long deltaInSecond = nowInSecond - startTime;
                calculateTimeAndCost(deltaInSecond);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void calculateTimeAndCost(final long delta) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (delta >= 0) {
                    String rentedTime = TimeUtil.formatTime(delta);
                    tvRentedTime.setText(rentedTime);
                    double cost = calculateCost(delta);
                    String displayCost = String.format(Locale.getDefault(),
                            "%.2f", cost) + "元";
                    tvCost.setText(displayCost);
                }
            }
        });
    }

    private double calculateCost(long delta) {
        double hour = ((double) delta) / 3600;
        return price * hour;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //监听返回键，不可以退出当前Activity
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.return_ball)
    public void returnBall() {
        addReturnRecord();
    }

    /**
     * 添加一条归还记录
     */
    private void addReturnRecord() {
        JSONObject data = new JsonUtil.JsonBuilder()
                .put("ball_key", ballKey)
                .put("eq_key", eqKey)
                .put("door_id", doorId)
                .build();
        String url = getString(R.string.url_base) + getString(R.string.url_add_return_record);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1) {
                        Log.d(TAG, "onJsonObjectResponse: 添加归还记录成功！");
                        loopCheckReturnState();
                    } else {
                        ToastUtil.showToast("还球失败，请重试！");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    hideProgressDialog();
                }
            }

            @Override
            public void onFailure(String msg) {
                hideProgressDialog();
                Log.e(TAG, "onFailure: " + msg);
            }
        });
    }

    private void loopCheckReturnState() {
        isReturnSuccess = false;
        times = LOOP_TIMES;
        timer.schedule(new CheckReturnStateTask(), 0, 1000);
    }

    /**
     * 查询归还结果
     */
    private void checkReturnState() {
        final JSONObject data = new JsonUtil.JsonBuilder()
                .put("ball_key", ballKey)
                .put("eq_key", eqKey)
                .build();

        String url = getString(R.string.url_base) + getString(R.string.url_check_return_state);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("请在柜子端点击“还球”后放入球具....");
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1 && !isReturnSuccess) {//只处理第一次符合条件的响应
                        rentTime = jsonObject.getLong("time");//这里可能会抛出异常
                        cost = jsonObject.getDouble("cost");
                        isReturnSuccess = true;
                        hideProgressDialog();
                    } else {//忽略其他响应
                        Log.d(TAG, "checkReturnState: ignore");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "checkReturnState: ", e);
                }

            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.showToast(msg);
                hideProgressDialog();
            }
        });

    }

    private void onTimeOut() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideProgressDialog();
                new AlertDialog.Builder(TimerActivity.this)
                        .setMessage(R.string.return_failed)
                        .setPositiveButton("好", null)
                        .create()
                        .show();
            }
        });

    }

    private void onReturnSuccess() {
        if (rentTime == -1) {
            Log.e(TAG, "onReturnSuccess: rentTime=-1");
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                resolveReturnResult(rentTime, cost);
            }
        });
    }

    /**
     * 处理归还结果，跳转到结算页面
     *
     * @param rentTime 租用时长
     * @param cost     总花费
     */
    private void resolveReturnResult(long rentTime, double cost) {
        Intent intent = new Intent(this, PayActivity.class);
        intent.putExtra(Const.Extra.TOTAL_COST, cost);
        intent.putExtra(Const.Extra.RENT_TIME, rentTime);
        startActivity(intent);
        finish();
    }

    class CheckReturnStateTask extends TimerTask {
        @Override
        public void run() {
            if (!isReturnSuccess && times > 0) {
                checkReturnState();
                Log.d(TAG, "Checking return state");
                times--;
            } else {
                cancel();
                if (isReturnSuccess) {
                    Log.d(TAG, "stop checking,return succeed!");
                    onReturnSuccess();
                } else {
                    Log.d(TAG, "stop checking,time out!");
                    onTimeOut();
                }
            }

        }
    }
}
